<?php 
require_once APPPATH.'controllers/app.php';
class Projects extends App {
    function __construct() {
        parent::__construct();
        $this->load->database();
        $this->load->library('grocery_CRUD');
    }
    function index(){
        $crud = new grocery_CRUD();
        $crud->set_subject('Dự án');
        $crud->set_table('tblprojects');
        //$crud->where('tblprojects.id','1');
        $crud->required_fields('name','customer','creatby','creatdate','begindate','enddate','pmid');
        $crud->columns('name','customer','creatby','creatdate','begindate','enddate','pmid');
        
        $crud->fields('name','customer','creatby','creatdate','begindate','enddate','pmid');
        $crud->set_relation('creatby','tblpersonnels','name');
        $crud->set_relation('pmid','tblpersonnels','name');
        $crud->display_as('name','Tên dự án');
        $crud->display_as('customer','Khách hàng');
        $crud->display_as('creatby','Người tạo');
        $crud->display_as('creatdate','Ngày tạo');
        $crud->display_as('begindate','Ngày bắt đầu');
        $crud->display_as('enddate','Ngày kết thúc');
        $crud->display_as('pmid','Trưởng dự án');
        $crud->callback_after_insert(array($this, '_addPM'));
        $crud->callback_after_update(array($this,'_editPM'));
        $crud->add_action('Phân bổ nhân sự', base_url().'assets/public/img/icon/settings.png','projects/assign_personnels');
        $output = $crud->render();
        $output->title = "Dự án";
        $output->content_title = "Dự án";
        $output->sb = $this->_menu;
        $this->load->view('common/layout_view',$output);
       // print_r($output);
    }
    
    function _addPM($post_array,$primary_key){
       $arr = array(
           'personnelid'=>$post_array['pmid'],
           'projectid'=>$primary_key,
           'roleid'=>'1'
            );
       $this->db->insert('tblmanager',$arr);
    }
    function _editPM($post_array,$primary_key){
       $arr = array(
           'personnelid'=>$post_array['pmid'],
           'projectid'=>$primary_key,
           'roleid'=>'1'
            );
       $this->db->update('tblmanager',$arr);
    }
    function end($pj_id){
        $this->db->where('id',$pj_id);
        $this->db->update('tblprojects',array('iscomplete'=>'1'));
        preUrl();
    }
    function delete($pj_id){
        $this->db->where('id',$pj_id);
        $this->db->delete('tblprojects');
        $this->db->where('projectid',$pj_id);
        $this->db->delete('tblworks');
        preUrl();
    }
    function evm($pj_id){
        $data['title'] = "Phân tích dự án ";
        $data['css_files'] = array();
        $data['js_files'] = array();
        $data['sb'] = $this->_menu;
        $data['content_title'] = "Phân tích dự án ";
        $data['pj_id'] = $pj_id;
        $this->load->model('work_model');
        $arr= $this->work_model->get_of_project($pj_id);
        $data['arr'] = $arr;
        $this->load->view('project/evm_view',$data);
    }
    function gantt($pj_id){
         $this->load->model('work_model');
         $arr= $this->work_model->get_of_project($pj_id);
         $arr = works_multi_level_table($arr);
         require_once (APPPATH.'jpgraph/jpgraph.php');
         require_once (APPPATH.'jpgraph/jpgraph_gantt.php');
         $data = array();
         $progress = array();
         for($i=0;$i<count($arr);$i++){
                 $data[] = array($i,ACTYPE_NORMAL,remove_vi($arr[$i]['name']).'-'.remove_vi($arr[$i]['personnelname']),$arr[$i]['beginonreality'],$arr[$i]['enddaywork'],'');
                 $progress[] = array($i,$arr[$i]['percent']/100);
         }
         $constrains = array();
         $graph = new GanttGraph();
         $graph->title->Set("Biểu đồ Gantt");
         // Setup scale
         $graph->ShowHeaders(GANTT_HYEAR | GANTT_HMONTH | GANTT_HDAY | GANTT_HWEEK);
         $graph->scale->week->SetStyle(WEEKSTYLE_FIRSTDAYWNBR);
         // Add the specified activities
         $graph->CreateSimple($data,$constrains,$progress);
         // .. and stroke the graph
         $graph->Stroke();
    }
    function assign_personnels($pj_id){
        $this->load_assign_personnels($pj_id);
    }
	/**
	     function ajax_assign_personnels_process(){// ham xu ly ajax them hoac cap nhat phan cong cap 1
        $is_ajax = $_REQUEST['is_ajax'];
     	if(isset($is_ajax) && $is_ajax){
            $this->load->model('project_model');
            $pj_id = $_REQUEST['pj_id'];
            $mydata = $_REQUEST['mydata'];
            $managerid = $_REQUEST['managerid'];
            $pns = @split('---', $mydata);
            $re = @split('---',$_REQUEST['str_re']); // str_se co dang id--soluong---id--soluong
            $ma = @split('---',$_REQUEST['str_ma']);
            // Cap nhat len truong nhom
            $this->db->query("UPDATE tblmanager set `roleid`='2' WHERE `id`='$managerid'");
            // Xoa phan cong nhan su va them lai
            $this->db->query("DELETE FROM tblmanager WHERE parent = '$managerid'");
            foreach ($pns as $p) {
                $arr = array(
                    'personnelid'=>$p,
                    'projectid'=>$pj_id,
                    'roleid'=>'3',
                    'parent'=>$managerid
                );
                $this->db->insert('tblmanager',$arr);
            }
            //Xoa phan cong cu va phan cong lai
            $this->db->query("DELETE FROM tblassigns WHERE managerid='$managerid'");
            // Them nguyen lieu va tai nguyen
            foreach ($ma as $m) {
                $a = @split('--',$m);
                if(count($a)>1){
                   $arr = array(
                    'materialid'=>$a[0],
                    'amount'=>$a[1],
                    'date'=>date('Y-m-d'),
                    'managerid'=>$managerid
                    );
                    $this->db->insert('tblassigns',$arr); 
                }       
            }
            foreach ($re as $r) {
                $a = @split('--',$r);
                if(count($a)>1){
                    $arr = array(
                        'resourceid'=>$a[0],
                        'amount'=>$a[1],
                        'date'=>date('Y-m-d'),
                        'managerid'=>$managerid
                    );
                    $this->db->insert('tblassigns',$arr);
                }
            }
            echo 'Cập nhật thành công';
            
        }else {
            echo 'Có lỗi xảy ra, vui lòng thử lại sau !';
        }
    }
	 * */
    function ajax_assign_personnels_process(){// ham xu ly ajax them hoac cap nhat phan cong c
        $is_ajax = $_REQUEST['is_ajax'];
     	if(isset($is_ajax) && $is_ajax){
            $this->load->model('project_model');
            $pj_id = $_REQUEST['pj_id'];
            $mydata = $_REQUEST['mydata'];
            $managerid = $_REQUEST['managerid'];
            $pns = @split('---', $mydata);
            $re = @split('---',$_REQUEST['str_re']); // str_se co dang id--soluong---id--soluong
            $ma = @split('---',$_REQUEST['str_ma']);
            // Cap nhat len truong nhom
            $this->db->query("UPDATE tblmanager set `roleid`='2' WHERE `id`='$managerid'");
            // Xoa phan cong nhan su va them lai ( sua thanh cap nhat lai manager)
         	//Tao ds personnelid de theo tac query IN
			 $pns_in = join(',', $pns);
			 $this->load->model('manager_model');
			 $pa_mn = $this->manager_model->getParent($managerid);
			 $this->db->query("UPDATE tblmanager set `parent`='$managerid'
							   WHERE `personnelid` IN ($pns_in) 
							          AND parent = '$pa_mn'
							   ");
			// Neu ko co bang ghi nao de update, tuc la nhan vien nay dc phan lan dau, tuc PM phan, ko can phai thua huong tu ai ca, thi them vao
			if($this->db->affected_rows()==0){
				foreach ($pns as $p) {
	                $arr = array(
	                    'personnelid'=>$p,
	                    'projectid'=>$pj_id,
	                    'roleid'=>'3',
	                    'parent'=>$managerid
	                );
	                $this->db->insert('tblmanager',$arr);
				}
			}
            //Xoa phan cong cu va phan cong lai
            $this->db->query("DELETE FROM tblassigns WHERE managerid='$managerid'");
            // Them nguyen lieu va tai nguyen
            foreach ($ma as $m) {
                $a = @split('--',$m);
                if(count($a)>1){
                   $arr = array(
                    'materialid'=>$a[0],
                    'amount'=>$a[1],
                    'date'=>date('Y-m-d'),
                    'managerid'=>$managerid
                    );
                    $this->db->insert('tblassigns',$arr); 
                }       
            }
            foreach ($re as $r) {
                $a = @split('--',$r);
                if(count($a)>1){
                    $arr = array(
                        'resourceid'=>$a[0],
                        'amount'=>$a[1],
                        'date'=>date('Y-m-d'),
                        'managerid'=>$managerid
                    );
                    $this->db->insert('tblassigns',$arr);
                }
            }
            echo 'Cập nhật thành công';
            
        } else {
            echo 'Có lỗi xảy ra, vui lòng thử lại sau !';
        }
    }
    function load_assign_personnels($pj_id){
        $this->load->model('project_model');
        $this->load->model('calender_model');
         $this->load->model('work_model');
        $name = $this->project_model->get_name($pj_id);
        $data['title'] = "Phân công nhân sự cho dự án ".$name;
        $data['css_files'] = array(base_url().'assets/public/css/reveal.css');
        $data['js_files'] = array(
            base_url().'assets/public/js/jquery.dualListBox-1.3.min.js',
            base_url().'assets/public/js/jquery.reveal.js'
        );
        $data['sb'] = $this->_menu;
        $data['content_title'] = "Phân công nhân sự cho dự án ".$name;
        $data['pj_id'] = $pj_id;
        $data['works'] = $this->work_model->get_works_free_of_project($pj_id);
        $data['resources'] = $this->project_model->get_resources();
        $data['materials'] = $this->project_model->get_materials();
        // Lay danh sach nhan vien ranh voi du an nay
        $this->load->model('personnel_model');
        $data['pn_free'] = null;//$this->personnel_model->get_for_assign_free($pj_id);
        $this->load->model('manager_model');        
        $data['managers'] = $this->manager_model->get_managers($pj_id);
        $data['pn_busy'] = $this->personnel_model->get_for_assign_busy($pj_id);
        $this->load->view('project/assign_personnel_view',$data);
    }
    function ajax_get_pn($pj_id,$type){// lau danh sach nhan vien tuong ung voi them moi hoac cap nhat : type
        $this->load->model('personnel_model');
        switch ($type) {
            case '1':// dang roi
               echo json_encode ("<option value='0'>Chọn trưởng nhóm</option>".arrTooptions(
                        $this->personnel_model->get_for_assign_free($pj_id),'name','id'));
                break;
            case '2'://dang lam viec
               echo json_encode ("<option value='0'>Chọn trưởng nhóm</option>".arrTooptions(
                        $this->personnel_model->get_boss_of_project($pj_id),'name','personnelid'));
                break;
            default:
                return null;
        }
        //echo json_encode('hahaha');
    }
    
    
    // Lay danh sach nhan vien va cong viec dang ban neu co dang li title
    function get_pn_boss($pj_id){
         $this->load->model('personnel_model');
         $str = (arrTooptions(
                        $this->personnel_model->get_for_assign_free($pj_id),'name','id'));
         $arr = $this->personnel_model->get_for_assign_busy($pj_id);
         foreach ($arr as $a) {
            $des = str_replace('<br/>','1&#013',$a['des']);
            $str .= "<option value='".$a['personnelid']."' title='$des'>".$a['personnelname'].' (Đang bận)</option>';
         }
         return($str); 
    }
    function ajax_get_pn_boss($pj_id){
         $this->load->model('personnel_model');
         $str .= " <option value='0'>Chọn phân công</option>";
         $str .= (arrTooptions(
                        $this->personnel_model->get_for_assign_free($pj_id),'name','id'));
         $arr = $this->personnel_model->get_for_assign_busy($pj_id);
         foreach ($arr as $a) {
            $des = str_replace('<br/>','1&#013',$a['des']);
            $str .= "<option value='".$a['personnelid']."' title='$des'>".$a['personnelname'].'--------Đang bận</option>';
         }
         echo json_encode($str); 
    }
    function ajax_get_pn_of_manager($managerid){
        $this->load->model('personnel_model');
        echo json_encode (arrTooptions(
                        $this->personnel_model->get_personnels_of_manager($managerid),'name','personnelid'));
        
    }
    function ajax_get_pn_free_manager($managerid){
        $this->load->model('personnel_model');
        echo json_encode (arrTooptions(
                        $this->personnel_model->get_personnels_free_manager($managerid),'name','id'));
    }
    function ajax_get_workid_of_boss($bossid,$pj_id){
        $arr = $this->db->query("SELECT workid,tblworks.name FROM tblmanager JOIN tblworks ON workid=tblworks.id WHERE personnelid='$bossid' AND tblmanager.projectid='$pj_id'")->result_array();
        echo json_encode("<option value='".$arr[0]['workid']."'>".$arr[0]['name']."</option>");
        //echo json_encode('<option>con me mi</option>');
    }
    function ajax_get_works_free_of_project($pj_id){
        $this->load->model('work_model');
         echo json_encode ("<option value='0'>Chọn công việc</option>".arrTooptions(
                        $this->work_model->get_works_free_of_project($pj_id),'name','id'));   
    }
    function ajax_get_resources_materials(){
        $this->load->model('project_model');
        $arr = $this->project_model->get_resources();
        $arr2 = $arr = $this->project_model->get_materials();
        echo json_encode(arrTooptions($arr,'name','id').'---'.arrTooptions2($arr2,'name','id','amount','amount'));
    }
    
    function get_resources_materials_of_pn_project($managerid) {
        $this->load->model('project_model');
        $arr = $this->project_model->get_resources_materials_of_pn_project($managerid);
        $str = '';
        foreach ($arr[0] as $a) {
            $str .="<option value='".$a['resourceid']."' amount='".$a['amount']."'>".$a['resourcename'].", Số lượng ".$a['amount']."</option>";
        }
        $str .= '------';        
        foreach ($arr[1] as $a) {
            $str .="<option value='".$a['materialid']."' amount='".$a['amount']."'>".$a['materialname'].", Số lượng ".$a['amount'].$a['unit']."</option>";
        }
        return $str;
    }
    function ajax_check_assign($managerid) {
        $arr = $this->db->query("SELECT status FROM tblmanager where id = '$managerid'")->result_array();
        echo (json_encode($arr[0]['status']));
    }
    
    function ajax_load_all($pj_id,$managerid){
         $str  = '';
         $this->load->model('personnel_model');
         if(is_admin()||  is_pm($pj_id)){
             // pn chua phan cong
             $arr_free = $this->personnel_model->get_for_assign_free($pj_id,$managerid);
             if(count($arr_free)>0) $str .= (arrTooptions($arr_free,'name','id'));
             $arr = $this->personnel_model->get_for_assign_but_busy($pj_id,$managerid);
             if($arr!=null||  count($arr)>0){
                    foreach ($arr as $a) {
                        $des = str_replace('<br/>','1&#013',$a['des']);
                        $str .= "<option value='".$a['personnelid']."' title='$des'>".$a['personnelname'].' (Đang bận)</option>';
                    }
             }
             $str .= '------';
             // pn da phan cong
             $arr_ = $this->personnel_model->get_free_with_manager($pj_id,$managerid);
             if(count($arr_)>0) $str .= (arrTooptions($arr_,'name','id'));
             $arr = $this->personnel_model->get_of_manager_busy($pj_id,$managerid);
             if($arr!=null){
                    foreach ($arr as $a) {
                        $des = str_replace('<br/>','1&#013',$a['des']);
                        $str .= "<option value='".$a['personnelid']."' title='$des'>".$a['personnelname'].' (Đang bận)</option>';
                    }
             }   
         }else {
             $pn_total = $this->personnel_model->get_personnels_of_parentmanager($pj_id,$managerid);
             $arr_pn = @split('--------------', $pn_total);
             $str .= $arr_pn[0].'------'.$arr_pn[1];
             
         }
         $str .= '------'.$this->get_resources_materials_of_pn_project($managerid);
         $this->load->model('manager_model');
         $str .= '------'.$this->manager_model->get_workid($managerid);
         echo json_encode($str);
    }
    function ajax_get_pn_of_parentmanager($managerid){
        $pj_id = $this->project_model->get_project_from_manager($managerid);
        $this->load->model('personnel_model');
        $arr = $this->personnel_model->get_personnels_of_parentmanager($managerid);
        $str = '';
        foreach ($arr as $k => $v) {
            $pns[$k]['des'] =  $this->personnel_model->get_work_busy_string($pj_id,$v['id'],null,$ma_without);
            if($pns[$k]['des']!='')
            $str .= "<option value='".$v['id']."' title='".$pns[$k]['des']."'>".$v['name']." (Đang bận)</option>"; 
            else $str .= "<option value='".$v['id']."'>". $v['name']."</option>"; 
            
        }
        return json_encode($str);
    }
}
?>
